<template>
  <div class="container">
    <!--上传按钮  -->
    <el-button type="primary" size="small" @click="dialogFormVisible = true"
      >新增用户</el-button
    >
    <!-- 表格table -->
    <el-table
      :data="userListPage"
      :header-cell-style="{ background: '#F5F7FA' }"
    >
      <el-table-column
        type="index"
        :index="indexNum"
        label="序号"
        align="center"
      />
      <el-table-column prop="userName" label="用户名" align="center" />
      <el-table-column prop="passWord" label="密码" align="center" />
      <el-table-column prop="userTel" label="联系方式" align="center" />
      <el-table-column prop="accountName" label="开户行" align="center" />
      <el-table-column prop="bankNumber" label="银行卡号" align="center" />
      <el-table-column prop="userType" label="用户类型" align="center" />
      <el-table-column fixed="right" label="操作" align="center">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            @click.prevent="editorUser(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            title="确定删除?"
            @confirm="deleteUserInfo(scope.row.id)"
          >
            <template #reference>
              <el-button type="text" size="small"> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      background
      v-model:currentPage="currentpage"
      :page-sizes="pageSizeDefault"
      :page-size="pageSize"
      layout="total,sizes, prev, pager, next, jumper"
      :total="userListLength"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
    </el-pagination>
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="editorVisible ? '编辑用户' : '新增用户'"
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        label-width="85px"
        class="container-form"
        label-position="left"
      >
        <el-form-item label="用户名">
          <el-input v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.passWord"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="form.userTel"></el-input>
        </el-form-item>
        <el-form-item label="开户行">
          <el-input v-model="form.accountName"></el-input>
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model="form.bankNumber"></el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select
            v-model="form.userType"
            class="m-2"
            clearable
            placeholder="请选择用户类型"
            size="large"
          >
            <el-option
              v-for="item in userTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">关闭</el-button>
          <el-button v-if="editorVisible" type="primary" @click="updateUserInfo"
            >提交</el-button
          >
          <el-button v-else type="primary" @click="addUserInfo">新增</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { getAllUserList, addUser, updateUser, deleteUser } from "@/api";
import { defineComponent, onMounted, ref, reactive } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {},
  setup() {
    const userList = ref([]);
    const userListPage = ref<any>([]);
    const currentpage = ref(1 as number);
    const pageSize = ref(3 as number);
    const pageSizeDefault = ref([3, 5, 10, 15, 20]);
    const userListLength = ref(0);
    const dialogFormVisible = ref(false);
    const editorVisible = ref(false);
    const oldPage = ref(-1);
    const form = reactive({
      userId: "",
      userName: "",
      passWord: "",
      userTel: "",
      accountName: "",
      bankNumber: "",
      userType: "",
    });
    const userTypeList = [
      {
        value: "0",
        label: "租客",
      },
      {
        value: "1",
        label: "物业",
      },
    ];

    // 初始化获取数据
    const initUserList = async () => {
      await getAllUserList().then((res) => {
        res.forEach((item: any) => {
          if (item.userType == 1) {
            item.userType = "物业";
          } else {
            item.userType = "租客";
          }
        });
        userList.value = res;
        userListLength.value = res.length;
        if (oldPage.value == -1) {
          handleCurrentChange(1);
        } else {
          handleCurrentChange(oldPage.value);
        }
      });
    };
    // ui组件table 序号
    const indexNum = (index: number) => {
      return (currentpage.value - 1) * pageSize.value + index + 1;
    };
    //处理数据,分页
    const handleTableData = () => {
      userListPage.value = userList.value.slice(
        (currentpage.value - 1) * pageSize.value,
        currentpage.value * pageSize.value
      );
    };
    // 每页显示多少条
    const handleSizeChange = (val: number) => {
      pageSize.value = val;
      handleTableData();
    };
    //点击中间页的按钮 执行的方法
    const handleCurrentChange = (val: number) => {
      oldPage.value = val;
      currentpage.value = val;
      handleTableData();
    };
    // 对话框关闭
    const close = () => {
      form.userName = "";
      form.userTel = "";
      form.accountName = "";
      form.bankNumber = "";
      form.userType = "";
      form.userId = "";
      dialogFormVisible.value = false;
    };
    // 点击×号关闭
    const closeDialog = () => {
      form.userName = "";
      form.userTel = "";
      form.accountName = "";
      form.bankNumber = "";
      form.userType = "";
      form.userId = "";
    };
    // 编辑用户
    const editorUser = (val: any) => {
      editorVisible.value = true;
      dialogFormVisible.value = true;
      form.userName = val.userName;
      form.passWord = val.passWord;
      form.userTel = val.userTel;
      form.accountName = val.accountName;
      form.userId = val.id;
      form.bankNumber = val.bankNumber;
      for (let i = 0; i < userTypeList.length; i++) {
        if (val.userType == userTypeList[i].label) {
          form.userType = userTypeList[i].value;
        }
      }
    };
    // 更新用户
    const updateUserInfo = async () => {
      if (form.userName == "" || form.userTel == "" || form.userType == "") {
        ElMessage.error("提交信息不完整！");
      } else {
        await updateUser(form).then((res) => {
          if (res.data === 1) {
            ElMessage.success("更新成功！");
          }
          form.userName = "";
          form.userTel = "";
          form.accountName = "";
          form.bankNumber = "";
          form.userType = "";
          dialogFormVisible.value = false;
          initUserList();
        });
      }
    };
    // 新增用户
    const addUserInfo = async () => {
      if (form.userName == "" || form.userTel == "" || form.userType == "") {
        ElMessage.error("提交信息不完整！");
      } else {
        await addUser(form).then((res) => {
          if (res.data === 1) {
            ElMessage.success("新增成功！");
          }
          form.userName = "";
          form.userTel = "";
          form.accountName = "";
          form.bankNumber = "";
          form.userType = "";
          dialogFormVisible.value = false;
          oldPage.value = -1;
          initUserList();
        });
      }
    };
    // 删除用户
    const deleteUserInfo = async (val: number) => {
      await deleteUser(val).then((res) => {
        if (res.data === 1) {
          ElMessage.success("删除用户成功！");
        }
        initUserList();
        // for (let i = 0; i < userListPage.value.length; i++) {
        //   if (userListPage.value[i].id == val) {
        //     userListPage.value.splice(i, 1); //删除不请求数据，直接在数组中删除
        //     userListLength.value = userListLength.value - 1;
        //     break;
        //   }
        // }
      });
    };
    onMounted(() => {
      initUserList();
    });
    return {
      userList,
      userListPage,
      indexNum,
      pageSize,
      pageSizeDefault,
      currentpage,
      userListLength,
      handleCurrentChange,
      handleSizeChange,
      editorUser,
      dialogFormVisible,
      form,
      userTypeList,
      updateUserInfo,
      addUserInfo,
      close,
      editorVisible,
      oldPage,
      deleteUserInfo,
      closeDialog,
    };
  },
});
</script>

<style lang="scss" scoped>
.container {
  display: block;
  .el-button {
    margin-bottom: 6px;
  }
  .el-table {
    margin-bottom: 20px;
  }
  .el-pagination {
    display: flex;
    justify-content: flex-end;
  }
}
</style>